package com.test.mybatis.util;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

public class ReflectUtil {
    /**
     * 转换字段
     *
     * @param entity
     * @param resultSet
     * @throws SQLException
     */
    public static void setProToBeanFromResult(Object entity, ResultSet resultSet) throws SQLException {

        ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
        int count = resultSetMetaData.getColumnCount();
        Field[] declaredFields = entity.getClass().getDeclaredFields();
        for (int i = 0; i < count; i++) {
            String columnName = resultSetMetaData.getColumnName(i + 1).replace("_", "").toUpperCase();
            for (int i1 = 0; i1 < declaredFields.length; i1++) {

                String fieldName = declaredFields[i1].getName().toUpperCase();

                if (columnName.equalsIgnoreCase(fieldName)) {
                    if (declaredFields[i1].getType().getSimpleName().equals("Integer")) {
                        setProToBean(entity, declaredFields[i1].getName(), resultSet.getInt(resultSetMetaData.getColumnName(i + 1)));
                    } else if (declaredFields[i1].getType().getSimpleName().equals("Long")) {
                        setProToBean(entity, declaredFields[i1].getName(), resultSet.getLong(resultSetMetaData.getColumnName(i + 1)));
                    } else if (declaredFields[i1].getType().getSimpleName().equals("String")) {
                        setProToBean(entity, declaredFields[i1].getName(), resultSet.getString(resultSetMetaData.getColumnName(i + 1)));
                    } else if (declaredFields[i1].getType().getSimpleName().equals("Date")) {
                        setProToBean(entity, declaredFields[i1].getName(), resultSet.getDate(resultSetMetaData.getColumnName(i + 1)));
                    } else if (declaredFields[i1].getType().getSimpleName().equals("Boolean")) {
                        setProToBean(entity, declaredFields[i1].getName(), resultSet.getBoolean(resultSetMetaData.getColumnName(i + 1)));
                    } else if (declaredFields[i1].getType().getSimpleName().equals("BigDecimal")) {
                        setProToBean(entity, declaredFields[i1].getName(), resultSet.getBigDecimal(resultSetMetaData.getColumnName(i + 1)));
                    }
                    break;
                }
            }
        }
    }


    private static void setProToBean(Object bean, String name, Object value) {
        try {
            Field field = bean.getClass().getDeclaredField(name);
            field.setAccessible(true);
            field.set(bean, value);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
